﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace DynaPrecision.Miscellaneous
{
	public class TokenizedReader
	{
		public TokenizedReader(StreamReader source)
		{
			_source = source;
		}

		private Queue<string> _buffer = new Queue<string>();

		private StreamReader _source;

		public bool IsNextStringAvailable
		{
			get
			{
				return _buffer.Count != 0 || (!_source.EndOfStream);
			}
		}
		public string NextString
		{
			get
			{
				if (IsNextStringAvailable)
				{
					if (_buffer.Count == 0)
					{
						ReadLine();
					}
					if (_buffer.Count != 0)
					{
						return _buffer.Dequeue();
					}
					else return null;
				}
				else
				{
					return null;
				}
			}
		}
		public IEnumerable<string> CurrentLine
		{
			get
			{
				while (_buffer.Count != 0)
				{
					yield return _buffer.Dequeue();
				}
			}
		}
		public void DiscardNextString()
		{
			if (IsNextStringAvailable)
			{
				if (_buffer.Count == 0)
				{
					ReadLine();
				}
				_buffer.Dequeue();
			}
		}
		public void DiscardThisLine()
		{
			_buffer.Clear();
		}
		public void DiscardNextLine()
		{
			ReadLine();
			_buffer.Clear();
		}
		private void ReadLine()
		{
			if (_buffer.Count != 0) return;
			else if (_source.EndOfStream) return;
			else
			{
				string temp = _source.ReadLine();
				foreach (var s in temp.Split())
				{
					if ((!string.IsNullOrEmpty(s)) && (!string.IsNullOrWhiteSpace(s)))
					{
						_buffer.Enqueue(s);
					}
				}
			}
		}

	}
}
